package com.design.twords.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.design.twords.R;
import com.design.twords.activity.BooklListActivity;
import com.design.twords.activity.ChangePlanActivity;
import com.design.twords.activity.LearnWordActivity;
import com.design.twords.activity.OcrActivity;
import com.design.twords.activity.WordListActivity;
import com.design.twords.activity.WordPlayActivity;
import com.design.twords.config.ConfigData;
import com.design.twords.config.ConstantValue;
import com.design.twords.controller.TimeController;
import com.design.twords.database.OcrWordsList;
import com.design.twords.database.UserConfig;
import com.design.twords.database.UserData;
import com.design.twords.entity.JsonYdWordDetail;
import com.design.twords.object.JsonBaiduWords;
import com.design.twords.utils.JsonBaidu;
import com.design.twords.utils.MyApplication;
import com.design.twords.utils.RecognizeService;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;


public class HomeFragment extends Fragment implements View.OnClickListener{

    private static final String TAG = "HomeFragment";

    private String centence;
    private ProgressDialog progressDialog;

    private TextView _day,_date,_day_words, listenWordNumb;
    private LinearLayout cre_word,bei_words,file_words;
    private RelativeLayout listenWordList;
    private Button startListen, clearListenWords;
    private ImageView img;

    private Uri imageUri, fileUri;
    private File cameraSavePath;

    private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";

    File file=new File(Environment.getExternalStorageDirectory(), "/temp.jpg");
    private StringBuilder stringBuilder;

    private final int REQUEST_CODE_TAKE_PICTURE = 1;
    private final int IMAGE_REQUEST_CODE = 2;
    private final int IMAGE_CROP = 3;


    private String[] week = new String[]
            {"Sunday","Monday","Tuesday","Wendesday","Thursday","Friday","Saturday"};
    private String[] items = new String[]{"拍照","从相册选择"};

    private boolean hasToken = false;

    private static final int PERMISSION_REQUESTCODE = 100;
    private static final int FAIL_TO_TOKEN = 101;
    private static final int ON_DEAL_WITH = 102;
    private static final int LOAD_WORD = 103;


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case FAIL_TO_TOKEN:
                    Toast.makeText(getContext(),"licence方式获取token失败", Toast.LENGTH_LONG).show();
                    break;
                case ON_DEAL_WITH:
                    showProgressDialog("正在处理中");
                    break;
                case LOAD_WORD:
                    showProgressDialog("正在前往背诵页面");
                    break;
            }
        }
    };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.home_fragment, container, false);
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //添加到Activity 列表中
        MyApplication.getInstance().addActivity(this.getActivity());
        initView();
        initListener();

        /*
        FanyiV3Yd.requestForYoudao("ss dd wsafys to ingdtervene in people 's aging process .", new CallBackListener() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG,response.body().string());
            }
        });*/

        cameraSavePath = new File(Environment.getExternalStorageDirectory().getPath() + "/tmep.jpg");

        if (!TimeController.isTheSameDay(TimeController.getCurrentTimeStamp(),ConfigData.getLastOcrStartTime())){
            Log.d(TAG,"is a new day");
            //清空每日听写表
            LitePal.deleteAll(OcrWordsList.class);

            ConfigData.setLastOcrStartTime(TimeController.getCurrentTimeStamp());
            UserData userData = new UserData();
            userData.setAdded(false);
            userData.updateAll();

        }


    }

    private void initListener() {
        cre_word.setOnClickListener(this);
        bei_words.setOnClickListener(this);
        file_words.setOnClickListener(this);

        listenWordList.setOnClickListener(this);
        startListen.setOnClickListener(this);
        clearListenWords.setOnClickListener(this);
    }

    public void initView(){
        _day = getActivity().findViewById(R.id._day);
        _date = getActivity().findViewById(R.id._date);
        _day_words = getActivity().findViewById(R.id._day_words);
        cre_word = getActivity().findViewById(R.id.cre_word);
        bei_words = getActivity().findViewById(R.id.bei_words);
        file_words = getActivity().findViewById(R.id.file_words);

        listenWordList = getActivity().findViewById(R.id.home_todaylistenwords);
        listenWordNumb = getActivity().findViewById(R.id.home_wordnumb);
        startListen = getActivity().findViewById(R.id.home_startlisten);
        clearListenWords = getActivity().findViewById(R.id.home_clear);

        img = getActivity().findViewById(R.id.home_img);

    }
    @Override
    public void onStart() {
        super.onStart();
        Calendar calendar = Calendar.getInstance();
        _date.setText(calendar.get(Calendar.DATE)+"");
        int i=calendar.get(Calendar.DAY_OF_WEEK);
        _day.setText(week[i-1]);
        centence = "Good Good Study, Day Day Up!!!";
        _day_words.setText(centence);


        List<OcrWordsList> all1 = LitePal.findAll(OcrWordsList.class);
        listenWordNumb.setText(all1.size()+"");

        initAccessToken();
    }


    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        AlertDialog.Builder builder;
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        switch (v.getId()){
            case R.id.cre_word:
                JudgePermission();

                builder = new AlertDialog.Builder(getActivity());
                if (!checkTokenStatus()) {
                    return;
                }
                builder.setTitle("请选择方式")
                        .setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                final int num=which;
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        switch (num){
                                            case 0:
                                                goCamera();
                                                break;
                                            case 1:
                                                goPhotoAlbum();
                                                break;
                                        }
                                        dialog.dismiss();
                                    }
                                },200);

                            }
                        })
                        .show();
                break;
            case R.id.bei_words:
                List<UserConfig> all = LitePal.where("userId = ?", ConfigData.getUserId()).find(UserConfig.class);
                if(all.size() > 0){
                    Message msg = new Message();
                    msg.what = LOAD_WORD;
                    handler.sendMessage(msg);
                    intent.setClass(getActivity(), LearnWordActivity.class);
                    startActivity(intent);
                    progressDialog.dismiss();
                }else{
                    intent.setClass(getActivity(), ChangePlanActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.file_words:
                intent.setClass(getActivity(), BooklListActivity.class);
                startActivity(intent);
                break;
            case R.id.home_todaylistenwords:
                intent.setClass(getActivity(), WordListActivity.class);
                intent.putExtra("floder_id", ConstantValue.OCR);
                intent.putExtra("sources", "ocr");
                startActivity(intent);
                break;
            case R.id.home_startlisten:
                List<OcrWordsList> all1 = LitePal.findAll(OcrWordsList.class);
                ArrayList<String> words = new ArrayList<>();
                for (OcrWordsList word :all1){
                    words.add(word.getWord());
                }
                intent.setClass(getActivity(), WordPlayActivity.class);
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("words",words);
                intent.putExtra("bundle",bundle);
                startActivity(intent);
                break;
            case R.id.home_clear:
                builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("提示")
                        .setMessage("正在清空今日听写列表")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                LitePal.deleteAll(OcrWordsList.class);
                                //LitePal.deleteAll(OcrWrodTrans.class);
                                Toast.makeText(getContext(),"已清空",Toast.LENGTH_LONG).show();
                                listenWordNumb.setText("0");
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();

                break;
        }


    }

    private boolean checkTokenStatus() {
        if(!hasToken){
            Toast.makeText(getContext(),"未获取Token",Toast.LENGTH_LONG).show();
        }
        return hasToken;
    }

    private void initAccessToken(){
        OCR.getInstance(getActivity().getApplicationContext()).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                hasToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                Message message = new Message();
                message.what = FAIL_TO_TOKEN;
                handler.sendMessage(message);

            }
        }, getActivity().getApplicationContext());
    }


    private void showProgressDialog(String content) {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setTitle("请稍后");
        progressDialog.setMessage(content);
        progressDialog.setCancelable(true);
        progressDialog.show();
    }

    //激活相册操作
    private void goPhotoAlbum() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
    }

    //激活相机操作
    private void goCamera() {
        //调用系统相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        //判断当前版本如果版本大于Android 5.0
        //需要添加临时权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            fileUri = FileProvider.getUriForFile(getContext(), "com.design.twords.fileprovider", cameraSavePath);
            //添加权限 这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            fileUri = Uri.fromFile(cameraSavePath);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
    }


    //对ActivityResult 进行处理
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        String photoPath;
        if(resultCode == Activity.RESULT_OK ) {
            final Intent intent=data;
            switch (requestCode){
                //拍照
                case REQUEST_CODE_TAKE_PICTURE:
                    /*
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        photoPath = String.valueOf(cameraSavePath);
                        Uri uri = FileProvider.getUriForFile(getContext(),"com.design.twords.fileprovider",file);
                        photoCrop(uri);

                    } else {
                        photoPath = fileUri.getEncodedPath();
                        photoCrop(fileUri);
                    }*/
                    photoPath = String.valueOf(cameraSavePath);
                    photoCrop(fileUri);
                    Log.d(TAG, photoPath);

                    //Glide.with(getActivity()).load(photoPath).into(img);
                    break;
                //相册获取图片
                case IMAGE_REQUEST_CODE:
                    //Uri selectedImage = intent.getData(); //获取系统返回的照片的Uri
                    /*
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContext().getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String path = cursor.getString(columnIndex);  //获取照片路径
                    cursor.close();
                    Log.i("image",path);
*/
                    photoCrop(intent.getData());

/*
                     showProgressDialog("正在处理中");
                    RecognizeService.recGeneralBasic(getActivity().getApplicationContext(), path,
                            new RecognizeService.ServiceListener() {
                                @Override
                                public void onResult(String result) {
                                    analyseJSON(result,new Gson());
                                }
                            });

                     */

                    break;
                case IMAGE_CROP:
                    if (imageUri != null){
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Message message = new Message();
                                message.what = ON_DEAL_WITH;
                                handler.sendMessage(message);

                                File file = null;
                                try {
                                    file = new File(new URI(imageUri.toString()));
                                } catch (URISyntaxException e) {
                                    e.printStackTrace();
                                }
                                //照片路径
                                String path = Objects.requireNonNull(file).getPath();
                                Log.i("path",path);
                                RecognizeService.recAccurateBasic(getActivity().getApplicationContext(), path,
                                        result -> {
                                            analyseJSON(result,new Gson());
                                        });
                                file.delete();

                                cameraSavePath.delete();
                            }
                        }).start();
                    }

                    break;
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    //将bitmap写入到文件中 返回文件名
    private String saveBitmapFile(Bitmap bitmap) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-mm-ss");
        String filename = simpleDateFormat.format(date);
        File file = new File(getContext().getFilesDir(),filename);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getContext().getFilesDir()+"/"+filename;

    }
    //分析ocr后的json数据
    public void analyseJSON(String msg, Gson gson){
        Log.i("msg",msg);
        JsonBaidu jsonBaidu = gson.fromJson(msg, JsonBaidu.class);
        if(jsonBaidu != null){
            List<JsonBaiduWords> wordsResult = jsonBaidu.getWords_result();
            stringBuilder = new StringBuilder();
            for(JsonBaiduWords words : wordsResult){
                String word = words.getWords();

                /*FanyiV3Yd.requestForYoudao(words.getWords(), new CallBackListener() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        isWord(response.body().string());
                    }
                });

                 */
                Log.d("msg_word",word);
                //if(word.length() >= 2 && word.matches("(\\d?[ ]*[',]?[a-zA-Z]+[ ]*[\\\\.]?)*")){
                //word = word.trim();

                if(word.length() >= 2){
                    if (word.contains("/")){
                        String[] split = word.split("/");
                        stringBuilder.append(split[0].trim() + "##");
                    }else if (word.contains("(")){
                        String[] split = word.split("\\(");
                        stringBuilder.append(split[0].trim() + "##");
                    }else {
                        stringBuilder.append(word.trim() + "##");
                    }


                }

            }
            progressDialog.dismiss();
            Intent intent1 = new Intent(getActivity(), OcrActivity.class);
            intent1.putExtra("analysis",stringBuilder.toString());
            startActivity(intent1);

        }
    }

    private void isWord(String json){
        Gson gson = new Gson();
        JsonYdWordDetail ydword = gson.fromJson(json, JsonYdWordDetail.class);
        if (ydword.isWord()) {
            stringBuilder.append(ydword.getQuery() + " ");
        }
    }


    private void JudgePermission(){
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED){
            // 请求申请权限
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.CAMERA},
                    PERMISSION_REQUESTCODE);
            // 未获得权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.CAMERA)) {
                //说明用户明确拒绝了某个权限，我们应该在这里做出提示给用户，说清楚此权限的用户
                Toast.makeText(getContext(),"没有权限",Toast.LENGTH_LONG).show();
                onStart();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != PERMISSION_REQUESTCODE) {
            Toast.makeText(getActivity(),"没有存储权限",Toast.LENGTH_LONG).show();
            onStart();
        }
    }

    //裁剪图片
    private void photoCrop(Uri uri){
        //调用系统图片裁剪
        Intent intent = new Intent("com.android.camera.action.CROP");
        //判断当前版本号
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        imageUri = Uri.fromFile(file);
        intent.setDataAndType(uri, "image/*");
        //设置可裁剪
        intent.putExtra("crop", true);
        //宽高比 1:1
        intent.putExtra("aspectX", 0);
        intent.putExtra("aspectY", 0);
        //裁剪图宽高
        //putExtra("outputX", 300);
        //intent.putExtra("outputY", 300);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, IMAGE_CROP);
    }


    @Override
    public void onDestroy() {

        super.onDestroy();
    }
}